<template>
  <div class="userinfo-box">
    <div class="title">个人信息</div>

    <div class="table">
      <div class="button">
        <el-button type="primary" :icon="Edit" class="edit-btn" @click="EditBtn()">修改信息</el-button>
        <el-button type="primary" class="recharge-btn" @click="RechargeBtn()">余额充值</el-button>
      </div>
      <el-descriptions class="table-box" :column="2" border size="large">
        <!-- <template #extra>
          <el-button type="primary">操作</el-button>
        </template> -->

        <!-- 用户名 -->
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <Avatar />
              </el-icon>
              用户名
            </div>
          </template>
          {{ user.username }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <Avatar />
              </el-icon>
              用户ID
            </div>
          </template>
          {{ user.user_id }}
        </el-descriptions-item>



        <!-- 性别 -->
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <Female />
              </el-icon>
              <el-icon>
                <Male />
              </el-icon>
              性别
            </div>
          </template>
          <el-tag size="small">{{ user.gender }}</el-tag>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">

              年龄
            </div>
          </template>
          {{ user.age }}
        </el-descriptions-item>

        <!-- 电话 -->
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              <el-icon>
                <iphone />
              </el-icon>
              电话
            </div>
          </template>
          {{ user.phone }}
        </el-descriptions-item>

        <!-- 用户密码 -->
        <!-- <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              密码
            </div>
          </template>
          {{ user.userpassword}}
          
        </el-descriptions-item> -->

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">

              地区
            </div>
          </template>
          {{ user.region }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              email
            </div>
          </template>
          {{ user.email }}
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">
              余额
            </div>
          </template>
          {{ balance }}
        </el-descriptions-item>

      </el-descriptions>
    </div>

    <!-- 修改信息表单： -->
    <el-dialog v-model="dialogFormVisible" title="修改用户信息" width="500">

      <el-form-item label="用户ID" :label-width="formLabelWidth">
        <el-input v-model="form.userId" disabled placeholder="系统自动填充" />
      </el-form-item>

      <!-- 填写修改信息 -->
      <el-form :model="form">
        <el-form-item label="用户名" :label-width="formLabelWidth">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="性别" :label-width="formLabelWidth">
          <el-radio-group v-model="form.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" :label-width="formLabelWidth">
          <el-input v-model="form.age" autocomplete="off" />
        </el-form-item>
        <el-form-item label="地区" :label-width="formLabelWidth">
          <el-input v-model="form.region" autocomplete="off" />
        </el-form-item>

        <el-form-item label="电话" :label-width="formLabelWidth">
          <el-input v-model="form.newPhone" autocomplete="off" />
          <div class="el-form-item__error" style="color: #909399; font-size: 11px;">修改该信息需要密码验证</div>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth">
          <el-input v-model="form.newEmail" autocomplete="off" />
          <div class="el-form-item__error" style="color: #909399; font-size: 11px;">修改该信息需要密码验证</div>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
          <el-input v-model="form.oldPassword" autocomplete="off" />
        </el-form-item>

        <el-form-item label="新密码" :label-width="formLabelWidth">
          <el-input v-model="form.newPassword" autocomplete="off" />
          <div class="el-form-item__error" style="color: #909399; font-size: 11px;">修改该信息需要密码验证</div>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false; resetUpload()">取消</el-button>
          <el-button type="primary" @click="dialogFormVisible = false; ConfirmBtn()">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 充值表单 -->
    <el-dialog v-model="rechargeDialogVisible" title="余额充值" width="400px">

      <!-- <el-form-item label="充值用户ID" :label-width="formLabelWidth">
        <el-input v-model="rechargeForm.userId" disabled placeholder="系统自动填充" />
      </el-form-item> -->


      <el-form :model="rechargeForm" label-width="100px" @close="handleRechargeClose">
        <el-form-item label="充值金额">
          <el-input v-model="rechargeForm.rechargeAmount" placeholder="请输入充值金额（元）" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="rechargeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleRechargeSubmit(); rechargeDialogVisible = false">确认充值</el-button>
      </template>
    </el-dialog>



  </div>
</template>

<script setup lang="ts">
// import { Iphone, Location, OfficeBuilding, Tickets, User } from "@element-plus/icons-vue";
// import type { ComponentSize } from "element-plus";
import { Edit } from '@element-plus/icons-vue'
import { postupdateUserInfo, postRecharge, getUserInfoAPI } from "@/api/user"
import { useUserStore } from "@/stores/user"
import { ref, reactive, onMounted } from "vue";
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const user = userStore.user;
const UserID = user.user_id
console.log(UserID)

const balance = ref('')
// 获取用户余额
const getUserInfo = async () => {
  const res = await getUserInfoAPI(UserID)
  balance.value = res.balance
}

// 编辑信息表单
const formLabelWidth = '180px'//输入框标题宽度
const dialogFormVisible = ref(false)
// 表单数据存储
const form = reactive({
  userId: "",
  username: "",
  gender: "",
  age: "",
  region: '',
  newPhone: "",
  newEmail: "",
  oldPassword: "",
  newPassword: ""
})
// 重置表单
const resetUpload = () => {
  console.log("取消按钮")
  // eslint-disable-next-line @typescript-eslint/no-unused-expressions
  form.userId = "",
    form.username = "",
    form.gender = "",
    form.age = "",
    form.region = "",
    form.newPhone = "",
    form.newEmail = "",
    form.oldPassword = "",
    form.newPassword = ""
}
const EditBtn = () => {
  console.log("编辑用户信息")
  dialogFormVisible.value = true;
  form.userId = UserID;
}


// 充值表单：
const rechargeDialogVisible = ref(false);
const rechargeForm = reactive({
  userId: "",//充值用户ID
  rechargeAmount: 0, // 充值金额数
});
// 充值按钮
const RechargeBtn = () => {
  console.log('点击充值')
  rechargeDialogVisible.value = true;
  rechargeForm.userId = UserID;
}
// 充值提交
const handleRechargeSubmit = async () => {
  // 校验金额是否合法
  if (rechargeForm.rechargeAmount <= 0) {
    ElMessage.error("请输入有效的充值金额");
    return;
  }
  console.log("充值表单数据:", rechargeForm)

  const res = await postRecharge(rechargeForm)

  if (res.message === "成功") {
    ElMessage.success("充值成功");
    getUserInfo()
  }
};
// 对话框关闭时重置表单
const handleRechargeClose = () => {
  rechargeForm.rechargeAmount = 0;
  rechargeForm.userId = "";
};


// 确认按钮
const ConfirmBtn = async () => {
  console.log("表单确认按钮，表单数据：", form);

  // 过滤掉空值（保留用户ID）
  const nonEmptyForm = {
    userId: form.userId, // 必须包含用户ID：修改信息接口参数为用户ID
    ...Object.fromEntries(
      Object.entries(form).filter(([key, value]) => key !== 'userId' && value !== "")
    )
  };
  // console.log("请求接口的数据：", nonEmptyForm);

  // 修改信息接口
  const res = await postupdateUserInfo(nonEmptyForm);
  if (res.message === "成功") {
    ElMessage.success('修改信息成功');

    // 实时更新页面用户数据：更新pinia仓库的用户数据
    userStore.setUser({
      ...userStore.user, // 保留原有数据
      ...nonEmptyForm // 合并修改后的字段
      //生成新的newData传入方法
      //       const newData = {
      //   ...userStore.user,
      //   ...nonEmptyForm
      // };
    });
  } else {
    ElMessage.error('修改信息失败');
  }
};

onMounted(() => {
  getUserInfo()
}
)
</script>

<style lang="scss" scoped>
.userinfo-box {
  width: 970px;
  margin-left: 30px;
  background: #fafafa;
  // border: 1px solid black;
  position: relative;
  /* 为子元素提供定位的上下文 */
  height: 700px;
  /* 固定高度，以便纵向居中 */
}

.title {
  font-size: 40px;
  font-weight: 400;
  letter-spacing: 0px;
  line-height: 44px;
  color: rgba(51, 51, 51, 1);
  margin: 40px;
  margin-left: 200px;
}

.table {
  width: 600px;
  height: 450px;
  padding: 10px;
  // border: 1px solid black;
  position: absolute;
  /* 使用绝对定位 */
  top: 50%;
  /* 距离顶部50% */
  left: 50%;
  /* 距离左边50% */
  transform: translate(-50%, -50%);
  /* 移动自身宽高的一半，从而实现真正的居中 */
}

.el-descriptions-item {
  line-height: 40px;
}

.table-box {
  height: 100%;
  margin-top: 20px;
}

.button {
  top: 0;
}
</style>
